package com.asm.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 执行 Linux 命令并返回结果 (可以远程操作)
 *
 * @author YKenan
 */
@Configuration
@ConfigurationProperties(prefix = "com.linux")
public class ExecLinux {

    private static final Logger log = LoggerFactory.getLogger(ExecLinux.class);

    /**
     * 链接 Linux 的参数
     * ip: ip地址
     * port: 端口号
     * username: 用户名
     * pwd: 密码
     */
    private String ip;
    private int port;
    private String username;
    private String pwd;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    /**
     * @param execLinux 本类, 传入时得到配置内容.
     * @param string    执行的命令
     * @return List<String>
     * @throws IOException IOException
     */
    public JSONObject getExecCommand(ExecLinux execLinux, String string) throws IOException {
        // 创建连接
        Connection connection = new Connection(execLinux.getIp(), execLinux.getPort());
        class Authenticate {
            private Boolean login(ExecLinux execLinux) {
                boolean flg = false;
                try {
                    Connection connection = new Connection(execLinux.getIp());
                    connection.connect();// 连接 //判断身份是否已经认证
                    if (!connection.isAuthenticationComplete()) {
                        // 加锁，防止多线程调用时线程间判断不一致，导致出现重复认证
                        synchronized (this) {
                            if (!connection.isAuthenticationComplete()) { // 进行身份认证
                                flg = connection.authenticateWithPassword(execLinux.getUsername(), execLinux.getPwd());
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return flg;
            }

        }

        // 创建返回的容器
        JSONObject result = new JSONObject();
        List<String> commandResult = new ArrayList<>();
        // 连接
        connection.connect();
        // 认证
        boolean authenticateWithPassword = connection.authenticateWithPassword(execLinux.getUsername(), execLinux.getPwd());
        Authenticate authenticate = new Authenticate();
        if (!authenticateWithPassword || !authenticate.login(execLinux)) {
            throw new IOException("Authentication failed.");
        } else {
            Session session = connection.openSession();
            session.execCommand(string, "utf-8");
            StreamGobbler stdout = new StreamGobbler(session.getStdout());
            StreamGobbler stderr = new StreamGobbler(session.getStderr());
            BufferedReader stdoutBuffer = new BufferedReader(new InputStreamReader(stdout));
            BufferedReader solderersBuffers = new BufferedReader(new InputStreamReader(stderr));
            log.info("Connecting to Linux >>>> " + string);
            result.put("commadn",string);
            for (String line = stdoutBuffer.readLine(); line != null; line = stdoutBuffer.readLine()) {
                commandResult.add(line + "\n");
            }
            for (String line = solderersBuffers.readLine(); line != null; line = solderersBuffers.readLine()) {
                log.error("Connecting to Linux >>>> " + line);
                commandResult.add(line);
            }
            result.put("commandResult",commandResult);
            stdoutBuffer.close();
            solderersBuffers.close();
            session.close();
        }
        connection.close();
        return result;
    }

    @Override
    public String toString() {
        return "ExecLinux{" +
                "ip='" + ip + '\'' +
                ", port=" + port +
                ", username='" + username + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

